package cc.wfu.infrastructure.persistent.repository;

import cc.wfu.domain.cart.model.entity.CartEntity;
import cc.wfu.domain.cart.repository.ICartRepository;
import cc.wfu.infrastructure.persistent.dao.ICartDao;
import cc.wfu.infrastructure.persistent.po.Cart;
import cc.wfu.types.snow.SnowflakeIdGenerator;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @Author: jia-qiang ljq1024.cc
 * @desc: 购物车仓储实现
 * @Date: 2024-06-13-19:58
 */
@Repository
public class CartRepository implements ICartRepository  {

    @Resource
    protected ICartDao cartDao;
    @Resource
    protected SnowflakeIdGenerator snowflakeIdGenerator;

    /**
     * 新增购物车
     * @param cartEntity 购物车实体
     */
    @Override
    public int addShopCart(CartEntity cartEntity) {

        // 1. 参数转换
        Cart cartReq = Cart.builder()
                .cartId(snowflakeIdGenerator.nextId())
                .userId(Long.valueOf(cartEntity.getUserId()))
                .sku(cartEntity.getSku())
                .productCover(cartEntity.getProductCover())
                .productMerchant(cartEntity.getProductMerchant())
                .productTitle(cartEntity.getProductTitle())
                .totalCount(cartEntity.getTotalCount())
                .amount(cartEntity.getAmount())
                .build();
        // 2. 新增
        return cartDao.addShopCart(cartReq);

    }

    /**
     * 查询购物车
     */
    @Override
    public List<CartEntity> queryShopCart(String userId) {
        List<Cart> carts = cartDao.queryShopCart(userId);
        if (carts.isEmpty()) {
            return Collections.emptyList();
        }
        List<CartEntity> response = new ArrayList<>(carts.size());
        for (Cart cart : carts) {
            CartEntity cartEntity = CartEntity.builder()
                        .userId(String.valueOf(cart.getUserId()))
                        .sku(cart.getCartId())
                    .cartId(String.valueOf(cart.getCartId()))
                        .productCover(cart.getProductCover())
                        .productMerchant(cart.getProductMerchant())
                        .productTitle(cart.getProductTitle())
                        .totalCount(cart.getTotalCount())
                        .amount(cart.getAmount())
                        .build();

            response.add(cartEntity);
        }
        return response;
    }

    @Override
    public int deleteCart(String userId, String cartId) {
        return cartDao.deleteCart(userId, cartId);
    }
}
